﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using BlueMarineWindowsFormsClient.InternalService;

namespace BlueMarineWindowsFormsClient
{
    public partial class frmBookingManagement : Form
    {
        private readonly frmMain _parent;
        private readonly Status _status;
        private InternalServiceClient _bookingManagement;
        private bool flagUpdateCust;

        public frmBookingManagement(frmMain p)
        {
            InitializeComponent();
            _parent = p;
            dtpBookingFrom.MinDate = DateTime.Now;
            dtpBookingTo.MinDate = dtpBookingFrom.Value.Add(new TimeSpan(1, 0, 0, 0));
            InitServiceClient();
            _status = new Status(lblStatus);
        }

        private void AbortServiceClient()
        {
            if (_bookingManagement.State == CommunicationState.Faulted)
            {
                _bookingManagement.Abort();
                InitServiceClient();
            }
        }

        private void BookingManager_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                switch (BookingManager.SelectedIndex)
                {
                    case 1:
                        cmbRoomTypeList();
                        ChoseCustomerBooking();
                        break;
                    case 2:
                        CheckinView();
                        break;
                    case 3:
                        gvSupply.DataSource = _bookingManagement.SupplyDetailsGet();
                        gvSupplyOrderView(null);
                        CheckIn checkIn =
                            _bookingManagement.CheckInGetById(int.Parse(txtOrderSupplyCheckinSelectedId.Text));
                        bool ds = checkIn.CheckInEmployee > 0;
                        gvSupplyOrder.Enabled = ds;
                        gvSupply.Enabled = ds;
                        break;
                    case 4:
                        break;
                }
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void frmBookingManagement_FormClosed(object sender, FormClosedEventArgs e)
        {
            _parent.Dispose();
        }

        private void frmBookingManagement_Load(object sender, EventArgs e)
        {
            CustomerView();
            var buttonColumn = new DataGridViewButtonColumn
                                   {
                                       HeaderText = "Action",
                                       Name = "SelectedRoom",
                                       Text = "+",
                                       UseColumnTextForButtonValue = true,
                                       AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                                   };
            gvRoom.Columns.Add(buttonColumn);
            gvRoom.CellClick += gvRoom_CellClick;
        }

        private void InitServiceClient()
        {
            _bookingManagement = new InternalServiceClient("WSHttpBinding_IInternalService")
                                     {
                                         ClientCredentials =
                                             {
                                                 UserName = {UserName = _parent.UName, Password = _parent.PWord},
                                                 ServiceCertificate =
                                                     {
                                                         Authentication =
                                                             {
                                                                 CertificateValidationMode =
                                                                     X509CertificateValidationMode.None
                                                             }
                                                     }
                                             }
                                     };
        }

        private void btnOrderSupplyAccept_Click(object sender, EventArgs e)
        {
            try
            {
                var listSupply = (List<vSupplyOrder>) gvSupplyOrder.DataSource;
                if (listSupply.Count < 1) throw new ArgumentNullException();
                var lstSupplyId = new List<int>();
                foreach (vSupplyOrder vso in listSupply)
                {
                    for (int i = 0; i < vso.SupplyNumber; i++)
                    {
                        lstSupplyId.Add(vso.SupplyDetailID);
                    }
                }

                bool result = _bookingManagement.SuppliesAdd(lstSupplyId,
                                                             int.Parse(txtOrderSupplyCheckinSelectedId.Text));
                if (result)
                {
                    _status.SUCCESS("Accept order supply");
                    btnOrderSupplyAccept.Enabled = false;
                    return;
                }
                _status.FAIL("Accept order supply");
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void btnOrderSupplyNew_Click(object sender, EventArgs e)
        {
            btnOrderSupplyAccept.Enabled = true;
            btnOrderSupplyRemove.Enabled = true;
            lblTotalAmount.Text = "_ _ _";
            btnOrderSupplyAccept.Enabled = true;
            gvSupplyOrderView(null);
        }

        private void btnOrderSupplyRemove_Click(object sender, EventArgs e)
        {
            var lstsupply = (List<vSupplyOrder>) gvSupplyOrder.DataSource;
            if (lstsupply.Count < 1) throw new ArgumentNullException();
            DataGridViewSelectedRowCollection rows = gvSupplyOrder.SelectedRows;
            foreach (DataGridViewRow row in rows)
            {
                lstsupply.RemoveAt(row.Index);
            }
            gvSupplyOrderView(lstsupply);
            CalTotalAmount(lstsupply);
        }

        private void gvSupply_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0) return;
                DataGridViewCellCollection cells = gvSupply.Rows[e.RowIndex].Cells;
                int id = int.Parse(cells["SupplyDetailID"].Value.ToString());
                decimal price = decimal.Parse(cells["SupplyPrice"].Value.ToString());
                string name = cells["SupplyName"].Value.ToString();
                var listSupply = (List<vSupplyOrder>) gvSupplyOrder.DataSource;

                bool flg = true;
                if (listSupply.Count > 0)
                {
                    foreach (vSupplyOrder vSupplyOrder in listSupply)
                    {
                        if (vSupplyOrder.SupplyDetailID == id)
                        {
                            vSupplyOrder.SupplyNumber++;
                            flg = false;
                            break;
                        }
                    }
                }
                else
                {
                    listSupply = new List<vSupplyOrder>();
                }
                if (flg)
                {
                    var supplyOrder = new vSupplyOrder
                                          {
                                              SupplyName = name,
                                              SupplyDetailID = id,
                                              SupplyPrice = price,
                                              SupplyNumber = 1
                                          };
                    listSupply.Add(supplyOrder);
                }
                gvSupplyOrderView(listSupply);
                CalTotalAmount(listSupply);
            }
            catch (Exception ex)
            {
                gvSupplyOrderView(null);
                _status.ERROR(ex.Message);
            }
        }


        private void CalTotalAmount(IEnumerable<vSupplyOrder> supplyOrders)
        {
            lblTotalAmount.Text = "_ _ _";
            decimal totalAmount = 0;
            foreach (vSupplyOrder vso in supplyOrders)
            {
                totalAmount = totalAmount + vso.SupplyPrice*vso.SupplyNumber;
            }
            lblTotalAmount.Text = totalAmount.ToString();
        }

        private void btnOrderSuplyNameSearch_Click(object sender, EventArgs e)
        {
            try
            {
                gvSupply.DataSource = _bookingManagement.SupplyDetailsGetByName(txtOrderSupplyName.Text);
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void btnCheckoutBookingIdSearch_Click(object sender, EventArgs e)
        {
            try
            {
                gvCheckoutCheckin.DataSource =
                    _bookingManagement.CheckInsGetByBookingId(int.Parse(txtCheckoutBookingId.Text));
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }


        private void gvSupplyOrder_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            DataGridViewCell cell = gvSupplyOrder.Rows[e.RowIndex].Cells["Quantity"];
            var lst = (List<vSupplyOrder>) gvSupplyOrder.DataSource;
            int number = int.Parse(cell.Value.ToString());
            if (number == 1)
            {
                lst.RemoveAt(e.RowIndex);
                gvSupplyOrderView(lst);
            }
            else
            {
                cell.Value = number - 1;
            }
            CalTotalAmount(lst);
        }

        private void btnCheckOutGenBill_Click(object sender, EventArgs e)
        {
            try
            {
                var lst = (List<CheckIn>) gvCheckoutCheckin.DataSource;
                List<int> chIds = lst.Select(p => p.CheckInID).ToList();
                List<vBill> bills = _bookingManagement.BillGetByCheckins(chIds);
                vBillBindingSource.DataSource = bills;
                rptCheckOutBill.RefreshReport();
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void gvCheckoutCheckin_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void reportViewer1_Load(object sender, EventArgs e)
        {
        }

        private void btnCheckinRoomIdSearch_Click(object sender, EventArgs e)
        {
            try
            {
                List<CheckIn> lst = _bookingManagement.CheckInsIncome();
                string id = txtCheckinRoomId.Text;
                if (id.Trim() != "")
                {
                    lst = lst.Where(p => p.RoomID == int.Parse(id)).ToList();
                }
                gvCheckinView(lst);
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void gvSupplyOrder_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void btnCheckOutCheckin_Click(object sender, EventArgs e)
        {
            try
            {
                var lst = (List<CheckIn>) gvCheckoutCheckin.DataSource;
                List<int> chIds = lst.Select(p => p.CheckInID).ToList();
                List<vBill> bills = _bookingManagement.CheckOutByCheckins(chIds, _parent.UName, _parent.PWord);

                if (bills.Count > 0)
                {
                    _status.SUCCESS("Checked bill");
                    rptCheckOutBill.LocalReport.ReportEmbeddedResource =
                        "BlueMarineWindowsFormsClient.Report.rptBillChecked.rdlc";
                    vBillBindingSource.DataSource = bills;
                    rptCheckOutBill.RefreshReport();
                    return;
                }


                // var lst = (List<CheckIn>) gvCheckoutCheckin.DataSource;
                // List<int> ids = lst.Select(p => p.CheckInID).ToList();
                //var result = _bookingManagement.CheckOutByCheckins(ids, _parent.UName, _parent.PWord);
                // if (result)
                // {
                //     _status.SUCCESS("Check out");
                //     return;
                // }
                _status.FAIL("Checked Bill");
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        #region "BOOKING"

        private void BookingRoomSearch()
        {
            try
            {
                var rt = (RoomType) cmbBookingRoomType.SelectedItem;
                List<vRoomInfo> listRoom = _bookingManagement.RoomsSearch(dtpBookingFrom.Value, dtpBookingTo.Value,
                                                                          rt.RoomTypeID, 0,
                                                                          0, false, false, false);
                gvRoom.DataSource = listRoom;
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void btnBooking_Click(object sender, EventArgs e)
        {
            try
            {
                var lstRoomID = new List<int>();
                int customerid = int.Parse(lblBookingCustomerId.Text);
                if (customerid > 0)
                {
                    for (int i = 0; i < lstBookingRoomSelected.Items.Count; i++)
                    {
                        lstRoomID.Add(int.Parse(lstBookingRoomSelected.Items[i].ToString()));
                    }

                    if (_bookingManagement.BookingAdd(customerid, lstRoomID, dtpBookingFrom.Value, dtpBookingTo.Value,
                                                      _parent.UName, _parent.PWord))
                    {
                        _status.SUCCESS("Add Booking");
                        BookingRoomSearch();
                        lstBookingRoomSelected.Items.Clear();
                    }
                }
                else
                    _status.ERROR("You have to chose a Customer!");
            }
            catch (Exception ex)
            {
                AbortServiceClient();
                _status.ERROR(ex.Message);
            }
        }

        private void btnBookingRoomSearch_Click(object sender, EventArgs e)
        {
            BookingRoomSearch();
        }

        private void btnRemoveRoom_Click(object sender, EventArgs e)
        {
            lstBookingRoomSelected.Items.Remove(lstBookingRoomSelected.SelectedItem);
        }

        private void cmbRoomTypeList()
        {
            try
            {
                List<RoomType> listRoomType = _bookingManagement.RoomTypesGet();
                cmbBookingRoomType.DataSource = listRoomType;
                cmbBookingRoomType.DisplayMember = "RoomTypeTitle";
                cmbBookingRoomType.ValueMember = "RoomTypeID";
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void dtpBookingFrom_ValueChanged(object sender, EventArgs e)
        {
            dtpBookingTo.MinDate = dtpBookingFrom.Value.Add(new TimeSpan(1, 0, 0, 0));
        }

        private void gvRoom_CellClick(object sender, EventArgs e)
        {
        }

        private void gvRoom_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewColumn dataGridViewColumn = gvRoom.Columns["SelectedRoom"];
            if (dataGridViewColumn != null && e.ColumnIndex == dataGridViewColumn.Index)
            {
                if (gvRoom.CurrentRow != null && e.RowIndex == gvRoom.CurrentRow.Index)
                {
                    int roomIDselected =
                        int.Parse(gvRoom.Rows[gvRoom.CurrentRow.Index].Cells["gvRoomRoomID"].Value.ToString());
                    lstBookingRoomSelected.Items.Remove(roomIDselected);
                    lstBookingRoomSelected.Items.Add(roomIDselected);
                }
            }
        }

        #endregion

        #region "CHECKIN"

        private void gvCheckinView(List<CheckIn> checkIns)
        {
            gvCheckin.DataSource = new List<CheckIn>();

            if (checkIns != null)
            {
                gvCheckin.DataSource = checkIns;
            }
        }

        private void btnCheckinDelete_Click(object sender, EventArgs e)
        {
            try
            {
                var lst = (List<CheckIn>) gvCheckin.DataSource;
                int chkId = int.Parse(txtSelectedCheckinId.Text);

                if (lst.First(p => p.CheckInID == chkId).Available)
                {
                    _status.FAIL("Can not Delete available checkin");
                    return;
                }

                DialogResult t = MessageBox.Show(string.Format("Delete Check In: {0} ", chkId), "Warning",
                                                 MessageBoxButtons.OKCancel);
                if (t == DialogResult.OK)
                {
                    if (_bookingManagement.CheckInRemove(chkId))
                    {
                        _status.SUCCESS(string.Format("Delete Check In: {0}", chkId));
                        CheckinView();
                        return;
                    }
                    _status.FAIL(string.Format("Delete Check In: {0}", chkId));
                }

                gvCheckinView(lst);
            }
            catch (Exception ex)
            {
                AbortServiceClient();
                _status.ERROR(ex.Message);
            }
        }

        private void btnCheckinLock_Click(object sender, EventArgs e)
        {
            try
            {
                List<int> lst = gvCheckinGetCheckinIds();
                if (_bookingManagement.CheckinLock(lst))
                {
                    _status.SUCCESS("Lock checkin");
                    CheckinView();
                }
                else
                {
                    _status.FAIL("Lock checkin");
                }
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }


        private void btnCheckinOrderSupply_Click(object sender, EventArgs e)
        {
            BookingManager.SelectTab(tabOrderSupply);
        }

        private void CheckinView()
        {
            try
            {
                if (rdCheckinViewByCustomer.Checked)
                {
                    int customerid = int.Parse(lblCheckinCustomerId.Text);
                    if (customerid < 0)
                    {
                        _status.FAIL("You have to chose a customer!");
                        return;
                    }
                    gvCheckinView(_bookingManagement.CheckInsGetByCustomerId(customerid));
                }
                else if (rdCheckinViewByBooking.Checked)
                {
                    int bookingid = int.Parse(lblBookingId.Text);
                    if (bookingid < 0)
                    {
                        _status.FAIL("You have to chose a Booking!");
                        return;
                    }
                    gvCheckinView(_bookingManagement.CheckInsGetByBookingId(bookingid));
                }
                else
                {
                    gvCheckinView(_bookingManagement.CheckInsIncome());
                }
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void gvCheckin_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0) return;
                string bookingid = gvCheckin.Rows[e.RowIndex].Cells["gvCheckinBookingID"].Value.ToString();
                string checkinid = gvCheckin.Rows[e.RowIndex].Cells["gvCheckinCheckInID"].Value.ToString();
                Booking booking = _bookingManagement.BookingGet(int.Parse(bookingid));
                lblBookingId.Text = booking.BookingID.ToString();
                lblBookingDate.Text = booking.BookingDate.ToUniversalTime().ToString();
                lblTotalPayment.Text = booking.TotalPayment.ToString();


                Customer customer = _bookingManagement.CustomerGet(booking.CustomerID);
                lblCheckinCustomerName.Text = customer.CustomerName;
                lblCheckinCustomerId.Text = customer.CustomerID.ToString();
                lblCheckinCustomerIdNo.Text = customer.CustomerIdentifyNo;
                chbxCheckInCustomerSexMale.Checked = customer.CustomerSex;
                txtSelectedCheckinId.Text = checkinid;
                txtOrderSupplyCheckinSelectedId.Text = checkinid;

                CheckIn checkIn = _bookingManagement.CheckInGetById(int.Parse(checkinid));
                txtGuestInfo.Text = checkIn.GuestInfo;

                DataGridViewSelectedRowCollection selectedlist = gvCheckin.SelectedRows;
                for (int i = 0; i < selectedlist.Count; i++)
                {
                    if (selectedlist[i].Cells["gvCheckinAvailable"].Value.ToString() == "True")
                    {
                        btnCheckinDelete.Enabled = false;
                        return;
                    }
                }
                btnCheckinDelete.Enabled = true;
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void gvCheckin_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0)
                    return;
                rdCheckinViewByBooking.Select();
                CheckinView();
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private List<int> gvCheckinGetCheckinIds()
        {
            DataGridViewSelectedRowCollection rows = gvCheckin.SelectedRows;
            var lst = new List<int>();
            for (int index = 0; index < rows.Count; index++)
            {
                string id = rows[index].Cells["gvCheckinCheckInID"].Value.ToString();
                lst.Add(int.Parse(id));
            }
            return lst;
        }

        private void rdCheckinView_CheckedChanged(object sender, EventArgs e)
        {
            CheckinView();
        }

        #endregion

        #region "CHECKOUT"

        private void btnCheckOut_Click(object sender, EventArgs e)
        {
            var lstCheckin = (List<CheckIn>) gvCheckin.DataSource;
            DataGridViewSelectedRowCollection selectedCheckin = gvCheckin.SelectedRows;
            List<CheckIn> lst = (selectedCheckin.Cast<DataGridViewRow>().Select(row => lstCheckin[row.Index])).ToList();
            gvCheckoutCheckin.DataSource = lst;
            BookingManager.SelectTab(tabCheckOut);
        }

        #endregion

        #region "CUSTOMER"

        private void btnCheckinAccept_Click(object sender, EventArgs e)
        {
            try
            {
                if (_bookingManagement.CheckinsAccept(int.Parse(txtSelectedCheckinId.Text), _parent.UName, _parent.PWord,
                                                      txtGuestInfo.Text))
                {
                    _status.SUCCESS("Accept Checkin");
                    CheckinView();
                    return;
                }
                _status.FAIL("Accept Checkin");
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void btnCustomerBooking_Click(object sender, EventArgs e)
        {
            errorProvider.SetError(txtCustomerEmail, "");
            BookingManager.SelectTab(tabBooking);
        }

        private void btnCustomerCheckIn_Click(object sender, EventArgs e)
        {
            errorProvider.SetError(txtCustomerEmail, "");
            BookingManager.SelectedTab = tabCheckIn;
        }

        private void btnCustomerCreate_Click(object sender, EventArgs e)
        {
            errorProvider.SetError(txtCustomerEmail, "");
            try
            {
                flagUpdateCust = false;
                string err;
                if (ValidData(txtCustomerName.Text.Trim(), txtCustomerPhone.Text.Trim(), txtCustomerEmail.Text.Trim(),
                              out err))
                {
                    string account;
                    if (_bookingManagement.CustomerAdd(out account, txtCustomerIdenfify.Text.Trim(),
                                                       txtCustomerName.Text.Trim(),
                                                       txtCustomerPhone.Text.Trim(), txtCustomerEmail.Text.Trim(),
                                                       chbxCustomerMale.Checked))
                    {
                        CustomerView();
                        txtCustomerSearchAccount.Text = account;
                        _status.SUCCESS("Add Customer");
                    }
                    else
                        _status.FAIL("Add Customer");
                }
                else
                    _status.ERROR(err);
            }
            catch (Exception ex)
            {
                AbortServiceClient();
                _status.ERROR(ex.Message);
            }
        }

        private void btnCustomerGuestInfoUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (_bookingManagement.CheckinModify(int.Parse(txtSelectedCheckinId.Text), txtGuestInfo.Text))
                {
                    _status.SUCCESS("Update Guest info");
                    return;
                }
                _status.FAIL("Update Guest info");
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void btnCustomerNameSearch_Click(object sender, EventArgs e)
        {
            errorProvider.SetError(txtCustomerEmail, "");
            string name = txtCustomerName.Text.Trim();
            if (name != "")
            {
                gvCustomer.DataSource = _bookingManagement.CustomersGet(name, "", "");
            }
        }

        private void btnCustomerSearchAccount_Click(object sender, EventArgs e)
        {
            ClearErrorProvider();
            try
            {
                string acc = txtCustomerSearchAccount.Text.Trim();
                gvCustomer.DataSource = _bookingManagement.CustomersGet("", "", acc);
            }
            catch (Exception ex)
            {
                _status.STATUS(ex.Message);
            }
        }

        private void btnCustomerSearchId_Click(object sender, EventArgs e)
        {
            ClearErrorProvider();
            string id = txtCustomerSearchId.Text.Trim();
            try
            {
                if (id != "")
                {
                    Customer cus = _bookingManagement.CustomerGet(int.Parse(id));
                    gvCustomer.DataSource = new List<Customer> {cus};
                    if (cus != null)
                    {
                        txtCustomerName.Text = cus.CustomerName;
                        txtCustomerIdenfify.Text = cus.CustomerIdentifyNo;
                        txtCustomerSearchAccount.Text = cus.CustomerAccount;
                        txtCustomerPhone.Text = cus.CustomerPhone;
                        txtCustomerEmail.Text = cus.CustomerEmail;
                        chbxCustomerMale.Checked = cus.CustomerSex;
                        txtCustomerId.Text = cus.CustomerID.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void btnCustomerUpdate_Click(object sender, EventArgs e)
        {
            errorProvider.SetError(txtCustomerEmail, "");
            try
            {
                flagUpdateCust = true;
                if (_bookingManagement.CustomerModify(int.Parse(txtCustomerId.Text), txtCustomerIdenfify.Text,
                                                      txtCustomerName.Text, txtCustomerPhone.Text,
                                                      txtCustomerEmail.Text.Trim(),
                                                      chbxCustomerMale.Checked))
                {
                    CustomerView();
                    _status.SUCCESS("Modify Customer");
                }
                else
                    _status.FAIL("Modify Customer");
            }
            catch (Exception ex)
            {
                AbortServiceClient();
                _status.ERROR(ex.Message);
            }
        }

        private void ChoseCustomerBooking()
        {
            try
            {
                if (int.Parse(lblBookingCustomerId.Text) < 0)
                {
                    _status.FAIL("You have to chose a customer!");
                    btnBooking.Enabled = false;
                    btnBookingRemoveRoom.Enabled = false;
                    lstBookingRoomSelected.Enabled = false;
                }
                else
                {
                    //BookingManager.SelectedTab = tabBooking;
                    btnBooking.Enabled = true;
                    btnBookingRemoveRoom.Enabled = true;
                    lstBookingRoomSelected.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void CustomerView()
        {
            gvCustomer.DataSource = _bookingManagement.CustomersGet("", "", "");
        }

        private void gvCustomer_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            try
            {
                string customerid = gvCustomer.Rows[e.RowIndex].Cells["CustomerID"].Value.ToString();
                string name = gvCustomer.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString();
                string idNo = gvCustomer.Rows[e.RowIndex].Cells["CustomerIdentifyNo"].Value.ToString();
                bool sex = Convert.ToBoolean(gvCustomer.Rows[e.RowIndex].Cells["CustomerSex"].Value);
                string phone = gvCustomer.Rows[e.RowIndex].Cells["CustomerPhone"].Value.ToString();
                string email = gvCustomer.Rows[e.RowIndex].Cells["CustomerEmail"].Value.ToString();
                string uname = gvCustomer.Rows[e.RowIndex].Cells["CustomerAccount"].Value.ToString();

                txtCustomerSearchId.Text = customerid;
                txtCustomerIdenfify.Text = idNo;
                txtCustomerName.Text = name;
                chbxCustomerMale.Checked = sex;
                txtCustomerPhone.Text = phone;
                txtCustomerEmail.Text = email;
                txtCustomerSearchAccount.Text = uname;
                txtCustomerId.Text = customerid;

                lblBookingCustomerId.Text = customerid;
                lblBookingCustomerIdNo.Text = idNo;
                lblBookingCustomerName.Text = name;

                lblCheckinCustomerId.Text = customerid;
                lblCheckinCustomerIdNo.Text = idNo;
                lblCheckinCustomerName.Text = name;
                chbxCheckInCustomerSexMale.Checked = sex;
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }

        private void txtCustomerEmail_Leave(object sender, EventArgs e)
        {
            int idxA = txtCustomerEmail.Text.IndexOf("@", StringComparison.Ordinal);
            if (idxA > -1)
            {
                if (txtCustomerEmail.Text.IndexOf(".", idxA, StringComparison.Ordinal) > idxA)
                {
                    if (!flagUpdateCust)
                    {
                        if (_bookingManagement.CustomerEmailCheck(txtCustomerEmail.Text))
                        {
                            errorProvider.SetError(txtCustomerEmail, "");
                            return;
                        }
                        errorProvider.SetError(txtCustomerEmail, "Exist email address!");
                        return;
                    }
                    errorProvider.SetError(txtCustomerEmail, "");
                    return;
                }
            }
            errorProvider.SetError(txtCustomerEmail,
                                   "E-mail address must be valid e-mail address format. For example 'someone@example.com!' ");
        }

        private void txtCustomerPhone_Leave(object sender, EventArgs e)
        {
            string strPhone = txtCustomerPhone.Text;
            var rePhone = new Regex(@"^0+\d{2,3}-\d{3}-\d{4}$");
            //var rePhone = new Regex(@"^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$");
            if (rePhone.IsMatch(strPhone))
            {
                errorProvider.SetError(txtCustomerPhone, "");
                return;
            }
            errorProvider.SetError(txtCustomerPhone, "Phone number mus be valid format 0xx[x]-xxx-xxxx!");
        }

        private bool ValidData(string pCustomerName, string pCustomerPhone,
                               string pCustomerEmail, out string err)
        {
            if (pCustomerName.Trim() == "")
            {
                err = "Null data";
                return false;
            }

            if (!validPhoneEmail(pCustomerPhone, pCustomerEmail, out err))
                return false;

            err = "";
            return true;
        }

        public static bool validPhoneEmail(string phone, string newemail, out string err)
        {
            var rePhone = new Regex(@"^0+\d{2,3}-\d{3}-\d{4}$");
            if (!rePhone.IsMatch(phone))
            {
                err = "Phone number mus be valid format." + "0xx[x]-xxx-xxxx";
                return false;
            }
            int idxA = newemail.IndexOf("@", StringComparison.Ordinal);
            if (idxA == -1 || newemail.IndexOf(".", idxA, StringComparison.Ordinal) <= idxA)
            {
                err = "E-mail address must be valid e-mail address format. For example 'someone@example.com' ";
                return false;
            }
            err = "";
            return true;
        }

        public void ClearErrorProvider()
        {
            _status.STATUS("");
            errorProvider.SetError(txtCustomerPhone, "");
            errorProvider.SetError(txtCustomerEmail, "");
        }

        #endregion

        #region "MENU"

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var about = new frmAbout();
            about.ShowDialog(this);
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var t = new Thread(ThreadProc);
            t.Start();
            Close();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        public void ThreadProc()
        {
            Application.Run(new frmMain(_parent.UName, ""));
        }

        private void userInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var userinf = new frmUserInfo(_parent);
            userinf.ShowDialog(this);
        }

        #endregion

        #region "SUPPLY"

        //private void SupplyView()
        //{
        //    gvSupply.DataSource = _bookingManagement.SupplyDetailsGet();
        //}


        private void btnOrderSupplySeach_Click(object sender, EventArgs e)
        {
            try
            {
                List<vSupplyOrder> result =
                    _bookingManagement.SupplyOrdersGet(int.Parse(txtOrderSupplyCheckinSelectedId.Text));
                if (result.Count > 0)
                {
                    gvSupplyOrderView(result);
                    btnOrderSupplyAccept.Enabled = false;
                    btnOrderSupplyRemove.Enabled = false;
                    CalTotalAmount(result);
                    return;
                }

                btnOrderSupplyAccept.Enabled = true;
                btnOrderSupplyRemove.Enabled = true;
            }
            catch (Exception ex)
            {
                _status.ERROR(ex.Message);
            }
        }


        private void gvSupplyOrderView(List<vSupplyOrder> supplyOrders)
        {
            gvSupplyOrder.DataSource = new List<vSupplyOrder>();
            if (supplyOrders != null)
            {
                gvSupplyOrder.DataSource = supplyOrders;
            }
        }

        #endregion
    }
}